<template>
  <div class="map-container">
    <!-- 头部标题 -->
    <div class="map-header">
      <h1 class="map-title">
        <el-icon><LocationInformation /></el-icon>
        居民定位管理系统
      </h1>
      <div class="map-controls">
        <el-button type="primary" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button type="success" @click="locateCenter">
          <el-icon><Position /></el-icon>
          地图中心
        </el-button>
      </div>
    </div>

    <!-- 地图主体 -->
    <div class="map-content">

      <!-- 地图区域 -->
      <div class="map-area">
        <div id="baiduMap" class="baidu-map">
          <div style="
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
            color: white;
            font-size: 18px;
          ">
            🗺️ 地图加载中...
          </div>
        </div>
        
        <!-- 可伸缩地图工具栏 -->
        <div class="collapsible-toolbar" :class="{ 'expanded': toolbarExpanded }">
          <!-- 工具栏切换按钮 -->
          <div class="toolbar-toggle" @click="toggleToolbar" :title="toolbarExpanded ? '收起工具栏' : '展开工具栏'">
            <el-icon v-if="!toolbarExpanded" class="toggle-icon">
              <ArrowLeft />
            </el-icon>
            <el-icon v-else class="toggle-icon">
              <ArrowRight />
            </el-icon>
          </div>
          
          <!-- 工具栏内容 -->
          <div class="toolbar-content" v-show="toolbarExpanded">
            <!-- 搜索区域 -->
            <div class="toolbar-group">
              <div class="group-label">搜索</div>
              <div class="group-content">
                <el-input
                  v-model="searchText"
                  size="small"
                  placeholder="搜索居民姓名或地址"
                  style="width: 200px"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                <el-button size="small" type="success" @click="searchResidents" :disabled="!searchText">
                  搜索
                </el-button>
              </div>
            </div>
            
            <!-- 缩放控制 -->
            <div class="toolbar-group">
              <div class="group-label">缩放</div>
              <div class="group-content">
                <el-button-group size="small">
                  <el-button @click="zoomIn">
                    <el-icon><Plus /></el-icon>
                    放大
                  </el-button>
                  <el-button @click="zoomOut">
                    <el-icon><Minus /></el-icon>
                    缩小
                  </el-button>
                </el-button-group>
              </div>
            </div>
            
            <!-- 视图控制 -->
            <div class="toolbar-group">
              <div class="group-label">视图</div>
              <div class="group-content">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="showAllResidents"
                  :loading="loading"
                  :disabled="residents.length === 0"
                >
                  <el-icon><Position /></el-icon>
                  显示全部
                </el-button>
                <el-select
                  v-model="mapType"
                  size="small"
                  style="width: 100px; margin-left: 8px"
                  @change="changeMapType"
                >
                  <el-option label="普通" value="normal"></el-option>
                  <el-option label="卫星" value="satellite"></el-option>
                  <el-option label="混合" value="hybrid"></el-option>
                </el-select>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 实时统计面板 -->
        <div class="stats-panel">
          <div class="stat-card">
            <div class="stat-number">{{ totalResidents }}</div>
            <div class="stat-label">总居民</div>
          </div>
          <div v-if="searchText" class="stat-card" style="border-left: 4px solid #67C93A;">
            <div class="stat-number" style="color: #67C93A;">{{ filteredResidents.length }}</div>
            <div class="stat-label">搜索结果</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 居民详情弹窗 -->
    <el-dialog
      v-model="showResidentDetail"
      title="居民详细信息"
      width="600px"
      center
    >
      <div v-if="selectedResident" class="resident-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="姓名">{{ selectedResident.name }}</el-descriptions-item>
          <el-descriptions-item label="地址" :span="2">{{ selectedResident.address }}</el-descriptions-item>
          <el-descriptions-item label="经度">{{ selectedResident.longitude }}</el-descriptions-item>
          <el-descriptions-item label="纬度">{{ selectedResident.latitude }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedResident.phone || '暂无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <el-button @click="showResidentDetail = false">关闭</el-button>
        <el-button type="primary" @click="locateToResident">
          <el-icon><Position /></el-icon>
          定位到此居民
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, toRaw } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import {
  LocationInformation,
  Refresh,
  Position,
  Plus,
  Minus,
  Search,
  ArrowRight,
  ArrowLeft
} from '@element-plus/icons-vue'

// 响应式数据
const map = ref(null)
const markers = ref([])
const totalResidents = ref(0)
const searchText = ref('')
const selectedResidentId = ref(null)
const selectedResident = ref(null)
const showResidentDetail = ref(false)
const mapType = ref('normal')

// 居民数据
const residents = ref([])
const loading = ref(false)

// 工具栏展开状态
const toolbarExpanded = ref(false)

// 切换工具栏展开状态
const toggleToolbar = () => {
  toolbarExpanded.value = !toolbarExpanded.value
}

// 坐标验证函数
const isValidCoordinate = (lng, lat) => {
  if (lng == null || lat == null || lng === undefined || lat === undefined) {
    return false
  }
  
  const numLng = Number(lng)
  const numLat = Number(lat)
  
  const isLngValid = !isNaN(numLng) && isFinite(numLng) && numLng >= -180 && numLng <= 180 && numLng !== 0
  const isLatValid = !isNaN(numLat) && isFinite(numLat) && numLat >= -90 && numLat <= 90 && numLat !== 0
  
  return isLngValid && isLatValid
}

// 安全获取数字坐标
const getSafeCoordinate = (lng, lat) => {
  const numLng = Number(lng)
  const numLat = Number(lat)
  
  if (isValidCoordinate(lng, lat)) {
    return { lng: numLng, lat: numLat, valid: true }
  }
  
  return { lng: 0, lat: 0, valid: false }
}

// 获取居民列表
const getResidents = () => {
  loading.value = true
  
  axios.get('/resident/getAllResident')
    .then(resp => {
      const rawResidents = resp.data.map(r => toRaw(r))
      residents.value = rawResidents
      updateStatistics()
      ElMessage.success('居民数据加载成功')
      
      if (map.value) {
        setTimeout(() => {
          addResidentMarkers()
        }, 100)
      }
    })
    .catch(error => {
      ElMessage.error('获取居民数据失败，请检查后端服务')
      residents.value = []
      updateStatistics()
    })
    .finally(() => {
      loading.value = false
    })
}

// 计算属性
const filteredResidents = computed(() => {
  if (!searchText.value) return residents.value
  return residents.value.filter(resident => 
    resident.name.includes(searchText.value) || 
    resident.address.includes(searchText.value)
  )
})

onMounted(() => {
  getResidents()
  nextTick(() => {
    loadAmapScript()
  })
})

// 显示加载状态
const showLoadingState = () => {
  const mapContainer = document.getElementById('baiduMap')
  if (mapContainer) {
    mapContainer.innerHTML = `
      <div style="
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        color: #666;
        font-size: 16px;
      ">
        <div style="margin-bottom: 20px;">
          <div style="
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #409eff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
          "></div>
        </div>
        <div>正在加载地图...</div>
        <div style="font-size: 14px; margin-top: 10px; color: #999;">
          请稍等片刻
        </div>
      </div>
      <style>
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      </style>
    `
  }
}

// 加载高德地图脚本
const loadAmapScript = () => {
  if (window.AMap) {
    initMap()
    return
  }
  
  // 设置安全密钥（必须在加载脚本之前设置）
  window._AMapSecurityConfig = {
    securityJsCode: "99e7eee895ad13737ad188142d5dfa51"
  }
  
  // 声明异步加载回调函数
  window.onAmapLoad = function() {
    nextTick(() => {
      initMap()
    })
  }
  
  // 使用高德地图API 2.0版本
  const script = document.createElement('script')
  script.charset = "utf-8"
  script.src = "https://webapi.amap.com/maps?v=2.0&key=54997fab675c15f9118c2eae854f6df9&callback=onAmapLoad"
  script.async = true
  script.onerror = () => {
    ElMessage.error('地图加载失败，请检查Key配置和网络连接')
    showMapError()
  }
  
  document.head.appendChild(script)
}

// 显示地图错误信息
const showMapError = () => {
  const mapContainer = document.getElementById('baiduMap')
  if (mapContainer) {
    mapContainer.innerHTML = `
      <div style="
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        background: #f5f5f5;
        color: #666;
        font-size: 16px;
      ">
        <div style="margin-bottom: 20px;">
          <svg width="64" height="64" viewBox="0 0 24 24" fill="#ccc">
            <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
          </svg>
        </div>
        <div>地图加载失败</div>
        <div style="font-size: 14px; margin-top: 10px; color: #999;">
          请检查高德地图API Key配置和网络连接
        </div>
        <div style="margin-top: 20px;">
          <button onclick="location.reload()" style="
            background: #409eff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
          ">
            重新加载
          </button>
        </div>
      </div>
    `
  }
}





// 初始化地图
const initMap = () => {
  try {
    if (!window.AMap) {
      throw new Error('高德地图API未加载')
    }
    
    // 创建地图实例 - 使用API 2.0配置，默认中心为广东省
    map.value = new window.AMap.Map('baiduMap', {
      center: [113.280637, 23.125178], // 默认广州中心
      zoom: 10,
      zooms: [3, 18], // 设置缩放级别范围，3-18级
      mapStyle: 'amap://styles/normal', // 标准样式
      features: ['bg', 'point', 'road'], // 显示背景、兴趣点、道路
      animateEnable: true, // 启用地图动画
      doubleClickZoom: true, // 启用双击放大
      dragEnable: true, // 启用拖拽
      zoomEnable: true, // 启用缩放
      rotateEnable: false, // 禁用旋转
      pitchEnable: false // 禁用倾斜
    })
    
    // 地图加载完成事件
    map.value.on('complete', () => {
      ElMessage.success('地图加载成功')
      
      // 如果此时已有居民数据，则添加标记
      if (residents.value.length > 0) {
        setTimeout(() => {
          addResidentMarkers()
        }, 500)
      }
    })
    
    // 地图加载失败事件
    map.value.on('error', (error) => {
      ElMessage.error('地图加载失败，请检查网络连接')
      showMapError()
    })
    
  } catch (error) {
    ElMessage.error('地图初始化失败，请检查网络连接')
    showMapError()
  }
}

// 添加居民标记
const addResidentMarkers = () => {
  if (!map.value || !window.AMap) {
    return
  }
  
  // 清除现有标记
  clearMarkers()
  
  let validMarkersCount = 0
  let invalidMarkersCount = 0
  
  residents.value.forEach((resident, index) => {
    // 使用安全坐标获取函数
    const coord = getSafeCoordinate(resident.longitude, resident.latitude)
    
    if (!coord.valid) {
      invalidMarkersCount++
      return
    }
    
    try {
      // 创建标记点 - 锚点定位样式  
      const marker = new window.AMap.Marker({
        position: [coord.lng, coord.lat],
        title: resident.name,
        // 自定义锚点定位样式
        content: `
          <div style="
            position: relative;
            width: 30px;
            height: 40px;
            cursor: pointer;
            transform: translate(-50%, -100%);
          ">
            <!-- 锚点主体 -->
            <div style="
              width: 30px;
              height: 30px;
              background-color: #ff4757;
              border: 3px solid #ffffff;
              border-radius: 50% 50% 50% 0;
              transform: rotate(-45deg);
              box-shadow: 0 4px 12px rgba(255, 71, 87, 0.5);
              position: absolute;
              top: 0;
              left: 0;
            "></div>
            <!-- 锚点中心点 -->
            <div style="
              width: 12px;
              height: 12px;
              background-color: #ffffff;
              border-radius: 50%;
              position: absolute;
              top: 6px;
              left: 6px;
              z-index: 2;
              box-shadow: 0 1px 3px rgba(0,0,0,0.3);
            "></div>
          </div>
        `,
        anchor: 'bottom-center'
      })
      
      // 添加点击事件
      marker.on('click', () => {
        selectResident(resident)
        showResidentDetail.value = true
      })
      
      // 创建信息窗口
      const infoWindow = new window.AMap.InfoWindow({
        content: `
          <div style="padding: 10px; min-width: 200px;">
            <h4 style="margin: 0 0 8px 0; color: #333;">${resident.name}</h4>
            <p style="margin: 4px 0; font-size: 12px; color: #666;">📍 ${resident.address}</p>
            <p style="margin: 4px 0; font-size: 12px; color: #666;">📞 ${resident.phone || '暂无'}</p>
          </div>
        `
      })
      
      // 添加鼠标悬停事件
      marker.on('mouseover', () => {
        infoWindow.open(map.value, marker.getPosition())
      })
      
      marker.on('mouseout', () => {
        infoWindow.close()
      })
      
      // 添加到地图
      map.value.add(marker)
      markers.value.push(marker)
      validMarkersCount++
      
    } catch (error) {
      invalidMarkersCount++
    }
  })
  
  // 显示统计消息
  if (invalidMarkersCount > 0) {
    ElMessage.warning(`部分居民坐标无效，已成功显示 ${validMarkersCount} 个标记`)
  }
  
  // 自动调整地图视野以包含所有标记
  if (markers.value.length > 0) {
    try {
      // 创建边界框
      const bounds = new window.AMap.Bounds()
      let validPoints = 0
      const validCoords = []
      
      residents.value.forEach(resident => {
        const coord = getSafeCoordinate(resident.longitude, resident.latitude)
        
        if (coord.valid && !isNaN(coord.lng) && !isNaN(coord.lat) && isFinite(coord.lng) && isFinite(coord.lat)) {
          bounds.extend([coord.lng, coord.lat])
          validCoords.push([coord.lng, coord.lat])
          validPoints++
        }
      })
      
      if (validPoints > 0) {
        // 设置地图视野 - 使用简化方式避免NaN错误
        if (validPoints === 1) {
          // 如果只有一个点，设置中心和缩放
          const coord = validCoords[0]
          map.value.setZoomAndCenter(12, coord)
        } else {
          // 多个点时使用边界，添加更多验证
          try {
            // 验证边界是否有效 - 使用相同的访问方式
            let southwest, northeast
            
            try {
              southwest = bounds.getSouthWest()
              northeast = bounds.getNorthEast()
            } catch (e) {
              throw new Error('边界访问方法失败')
            }
            
            // 检查坐标属性的不同可能性
            const swLng = southwest?.lng || southwest?.getLng?.() || southwest?.longitude
            const swLat = southwest?.lat || southwest?.getLat?.() || southwest?.latitude
            const neLng = northeast?.lng || northeast?.getLng?.() || northeast?.longitude
            const neLat = northeast?.lat || northeast?.getLat?.() || northeast?.latitude
            
            if (southwest && northeast && 
                !isNaN(swLng) && !isNaN(swLat) &&
                !isNaN(neLng) && !isNaN(neLat)) {
              map.value.setBounds(bounds, false, [50, 50, 50, 50])
            } else {
              throw new Error(`边界坐标无效`)
            }
          } catch (boundsError) {
            // 计算中心点
            const avgLng = validCoords.reduce((sum, coord) => sum + coord[0], 0) / validCoords.length
            const avgLat = validCoords.reduce((sum, coord) => sum + coord[1], 0) / validCoords.length
            map.value.setZoomAndCenter(11, [avgLng, avgLat])
          }
        }
      } else {
        map.value.setZoomAndCenter(10, [116.404, 39.915])
      }
    } catch (error) {
      map.value.setZoomAndCenter(10, [116.404, 39.915])
    }
  }
}

// 清除标记
const clearMarkers = () => {
  markers.value.forEach(marker => {
    map.value.remove(marker)
  })
  markers.value = []
}

// 更新统计信息
const updateStatistics = () => {
  totalResidents.value = residents.value.length
}

// 选择居民
const selectResident = (resident) => {
  selectedResidentId.value = resident.id
  selectedResident.value = resident
}

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

// 刷新数据
const refreshData = () => {
  ElMessage.info('正在刷新数据...')
  getResidents()
}

// 回到地图中心
const locateCenter = () => {
  if (map.value) {
    map.value.setZoomAndCenter(11, [116.404, 39.915])
    ElMessage.info('回到地图中心')
  }
}

// 放大地图
const zoomIn = () => {
  if (map.value) {
    map.value.zoomIn()
    ElMessage.info('地图放大')
  }
}

// 缩小地图
const zoomOut = () => {
  if (map.value) {
    map.value.zoomOut()
    ElMessage.info('地图缩小')
  }
}

// 搜索居民
const searchResidents = () => {
  if (!searchText.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  const filtered = filteredResidents.value
  if (filtered.length === 0) {
    ElMessage.info('未找到匹配的居民')
    return
  }
  
  ElMessage.success(`找到 ${filtered.length} 位匹配的居民`)
  
  // 如果只有一个结果，直接定位到该居民
  if (filtered.length === 1) {
    const resident = filtered[0]
    if (map.value) {
      const coord = getSafeCoordinate(resident.longitude, resident.latitude)
      if (coord.valid) {
        map.value.setZoomAndCenter(15, [coord.lng, coord.lat])
      } else {
        ElMessage.warning(`居民 ${resident.name} 坐标无效，无法定位`)
        return
      }
    }
    // 显示居民详情
    selectedResident.value = resident
    showResidentDetail.value = true
      } else {
      // 多个结果时，调整视野包含所有搜索结果
      if (map.value) {
        const bounds = new window.AMap.Bounds()
        let validSearchResults = 0
        
        filtered.forEach(r => {
          const coord = getSafeCoordinate(r.longitude, r.latitude)
          if (coord.valid) {
            bounds.extend([coord.lng, coord.lat])
            validSearchResults++
          }
        })
        
        if (validSearchResults > 0) {
          // 验证搜索结果边界
          const southwest = bounds.getSouthWest()
          const northeast = bounds.getNorthEast()
          
          if (southwest && northeast && 
              !isNaN(southwest.lng) && !isNaN(southwest.lat) &&
              !isNaN(northeast.lng) && !isNaN(northeast.lat)) {
            // 为搜索结果使用适中的padding和动画
            const padding = [60, 60, 80, 60] // 比显示全部稍小的padding
            map.value.setBounds(bounds, true, padding, 8) // 8秒动画时长
          } else {
            ElMessage.warning('搜索结果边界计算异常，使用默认视野')

          }
        } else {
          ElMessage.warning('搜索结果中没有有效的坐标数据')
        }
      }
    }
}

// 显示所有居民
const showAllResidents = () => {
  searchText.value = '' // 清空搜索
  
  if (!map.value || residents.value.length === 0) {
    ElMessage.warning('暂无居民数据可显示')
    return
  }
  
  // 添加loading状态
  const loadingMessage = ElMessage.info({
    message: '正在调整地图视野...',
    duration: 0, // 不自动关闭
    type: 'info'
  })
  
  try {
    // 过滤出有效坐标的居民
    const validResidents = residents.value.filter(r => {
      return isValidCoordinate(r.longitude, r.latitude)
    })
    

    
    if (validResidents.length === 0) {
      loadingMessage.close()
      ElMessage.warning('没有有效的坐标数据')
      return
    }
    
    if (validResidents.length === 1) {
      // 只有一个居民时，定位到该居民并设置合适的缩放级别
      const resident = validResidents[0]
      const coord = getSafeCoordinate(resident.longitude, resident.latitude)
      
      if (coord.valid) {
        map.value.setZoomAndCenter(13, [coord.lng, coord.lat])
      } else {
        throw new Error(`居民 ${resident.name} 坐标无效`)
      }
      
      setTimeout(() => {
        loadingMessage.close()
        ElMessage.success(`已定位到唯一居民：${resident.name}`)
      }, 800)
    } else {
      // 多个居民时，计算边界并添加更好的体验
      const bounds = new window.AMap.Bounds()
      let boundsValidCount = 0
      
      validResidents.forEach(r => {
        const coord = getSafeCoordinate(r.longitude, r.latitude)
        
        if (coord.valid && !isNaN(coord.lng) && !isNaN(coord.lat) && isFinite(coord.lng) && isFinite(coord.lat)) {
          bounds.extend([coord.lng, coord.lat])
          boundsValidCount++
        }
      })
      
      if (boundsValidCount === 0) {
        throw new Error('所有居民坐标都无效')
      }
      
      // 直接使用计算边界方案（已验证有效）
      
      const validCoords = []
      validResidents.forEach(r => {
        const coord = getSafeCoordinate(r.longitude, r.latitude)
        if (coord.valid) {
          validCoords.push([coord.lng, coord.lat])
        }
      })
      
      if (validCoords.length >= 2) {
        // 计算边界坐标
        const lngs = validCoords.map(c => c[0])
        const lats = validCoords.map(c => c[1])
        const minLng = Math.min(...lngs)
        const minLat = Math.min(...lats)
        const maxLng = Math.max(...lngs)
        const maxLat = Math.max(...lats)
        

        
        try {
          // 使用构造函数创建边界
          const newBounds = new window.AMap.Bounds([minLng, minLat], [maxLng, maxLat])
          
          // 使用更大的padding确保标记点不会贴边，提供更好的视觉体验
          const padding = [80, 80, 120, 80] // 上、右、下、左的padding
          
          // 设置地图边界，启用动画效果
          map.value.setBounds(newBounds, true, padding, 10)

          
        } catch (setBoundsError) {

          
          // 备用方案：计算中心点和合适的缩放级别
          const avgLng = validCoords.reduce((sum, coord) => sum + coord[0], 0) / validCoords.length
          const avgLat = validCoords.reduce((sum, coord) => sum + coord[1], 0) / validCoords.length
          const zoom = calculateOptimalZoom(validResidents)
          

          map.value.setZoomAndCenter(zoom, [avgLng, avgLat])
        }
        
      } else if (validCoords.length === 1) {
        // 只有一个坐标时，直接定位
        const coord = validCoords[0]
        map.value.setZoomAndCenter(13, coord)

        
      } else {
        throw new Error('没有有效的坐标数据')
      }
      
      // 延迟关闭loading并显示成功消息
      setTimeout(() => {
        loadingMessage.close()
        ElMessage.success(`已显示全部 ${validResidents.length} 位居民`)
      }, 1000)
    }
    
  } catch (error) {

    loadingMessage.close()
    ElMessage.error('地图视野调整失败，请重试')
  }
}

// 切换地图类型
const changeMapType = () => {
  if (!map.value) return
  
  // 移除现有图层
  const layers = map.value.getLayers()
  layers.forEach(layer => {
    if (layer.CLASS_NAME === 'AMap.TileLayer.Satellite' || layer.CLASS_NAME === 'AMap.TileLayer.RoadNet') {
      map.value.remove(layer)
    }
  })
  
  switch (mapType.value) {
    case 'satellite':
      // 添加卫星图层
      const satellite = new window.AMap.TileLayer.Satellite()
      map.value.add(satellite)
      break
    case 'hybrid':
      // 添加卫星图层和路网图层
      const satelliteHybrid = new window.AMap.TileLayer.Satellite()
      const roadNet = new window.AMap.TileLayer.RoadNet()
      map.value.add([satelliteHybrid, roadNet])
      break
    default:
      // 默认为标准地图，不需要额外操作
      break
  }
}

// 定位到指定居民
const locateToResident = () => {
  if (selectedResident.value && map.value) {
    const coord = getSafeCoordinate(selectedResident.value.longitude, selectedResident.value.latitude)
    if (coord.valid) {
      map.value.setZoomAndCenter(15, [coord.lng, coord.lat])
      showResidentDetail.value = false
      ElMessage.success(`已定位到居民：${selectedResident.value.name}`)
    } else {
      ElMessage.error(`居民 ${selectedResident.value.name} 坐标无效，无法定位`)
    }
  }
}

// 智能计算最佳缩放级别
const calculateOptimalZoom = (validResidents) => {
  if (validResidents.length <= 1) return 13
  
  // 过滤出有效坐标并计算范围
  const validCoords = []
  validResidents.forEach(r => {
    const coord = getSafeCoordinate(r.longitude, r.latitude)
    if (coord.valid) {
      validCoords.push(coord)
    }
  })
  
  if (validCoords.length === 0) return 10 // 默认缩放级别
  
  const lngs = validCoords.map(c => c.lng)
  const lats = validCoords.map(c => c.lat)
  
  const lngSpan = Math.max(...lngs) - Math.min(...lngs)
  const latSpan = Math.max(...lats) - Math.min(...lats)
  const maxSpan = Math.max(lngSpan, latSpan)
  
  // 根据坐标跨度智能选择缩放级别
  if (maxSpan > 5) return 6      // 跨省级别
  else if (maxSpan > 2) return 8  // 跨市级别  
  else if (maxSpan > 0.5) return 10 // 市区级别
  else if (maxSpan > 0.1) return 12 // 区域级别
  else if (maxSpan > 0.01) return 14 // 街道级别
  else return 16 // 社区级别
}






</script>

<style scoped>
.map-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  background: #0a0e1a;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
}

.map-header {
  height: 80px;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 40px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  border-bottom: 2px solid rgba(255,255,255,0.1);
}

.map-title {
  color: white;
  margin: 0;
  font-size: 32px;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 15px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}

.map-controls {
  display: flex;
  gap: 12px;
}

.map-content {
  flex: 1;
  display: flex;
  position: relative;
  width: 100%;
  min-height: 0; /* 重要：让flex子元素能够收缩 */
}

.map-area {
  width: 100%;
  height: 100%;
  position: relative;
  min-height: 500px; /* 确保最小高度 */
}

.baidu-map {
  width: 100%;
  height: 100%;
  min-height: 500px; /* 确保最小高度 */
  background: #f0f2f5; /* 添加背景色作为备用 */
}

/* 可伸缩工具栏 */
.collapsible-toolbar {
  position: absolute;
  top: 30px;
  right: 40px;
  background: rgba(0, 0, 0, 0.9);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.5);
  backdrop-filter: blur(20px);
  z-index: 1000;
  border: 1px solid rgba(255,255,255,0.15);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  width: 60px; /* 收缩时的宽度 */
  height: 60px; /* 收缩时的高度 */
}

.collapsible-toolbar.expanded {
  width: 380px; /* 展开时的宽度 */
  height: auto;
  min-height: 200px; /* 展开时的最小高度 */
}

.toolbar-toggle {
  position: absolute;
  top: 0;
  right: 0;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: rgba(74, 144, 226, 0.8);
  border-radius: 15px;
  transition: all 0.3s ease;
  z-index: 2;
}

.toolbar-toggle:hover {
  background: rgba(74, 144, 226, 1);
  transform: scale(1.05);
}

.toggle-icon {
  font-size: 20px;
  color: white;
  transition: transform 0.3s ease;
}

/* 移除旋转动画，因为我们现在使用不同的箭头图标 */

.toolbar-content {
  padding: 20px;
  padding-top: 80px; /* 为切换按钮留出空间 */
  display: flex;
  flex-direction: column;
  gap: 24px;
  opacity: 0;
  transform: translateY(-10px);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  transition-delay: 0.1s;
}

.collapsible-toolbar.expanded .toolbar-content {
  opacity: 1;
  transform: translateY(0);
}

.toolbar-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.group-label {
  font-size: 14px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.9);
  text-transform: uppercase;
  letter-spacing: 1px;
  border-bottom: 2px solid rgba(74, 144, 226, 0.6);
  padding-bottom: 6px;
}

.group-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

/* 工具栏按钮样式优化 */
.group-content .el-button {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  transition: all 0.3s ease;
}

.group-content .el-button:hover {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.4);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.group-content .el-button.el-button--primary {
  background: rgba(74, 144, 226, 0.8);
  border-color: rgba(74, 144, 226, 1);
}

.group-content .el-button.el-button--primary:hover {
  background: rgba(74, 144, 226, 1);
  border-color: rgba(74, 144, 226, 1);
}

.group-content .el-button.el-button--success {
  background: rgba(103, 201, 58, 0.8);
  border-color: rgba(103, 201, 58, 1);
}

.group-content .el-button.el-button--success:hover {
  background: rgba(103, 201, 58, 1);
  border-color: rgba(103, 201, 58, 1);
}

/* 输入框样式优化 */
.group-content .el-input {
  --el-input-bg-color: rgba(255, 255, 255, 0.1);
  --el-input-border-color: rgba(255, 255, 255, 0.2);
  --el-input-text-color: white;
  --el-input-placeholder-color: rgba(255, 255, 255, 0.6);
}

.group-content .el-input:hover {
  --el-input-border-color: rgba(255, 255, 255, 0.4);
}

.group-content .el-input.is-focus {
  --el-input-border-color: rgba(74, 144, 226, 1);
}

/* 选择器样式 */
.group-content .el-select {
  --el-select-input-color: white;
}

.stats-panel {
  position: absolute;
  top: 30px;
  left: 40px;
  display: flex;
  gap: 20px;
  z-index: 1000;
}

.stat-card {
  background: rgba(0, 0, 0, 0.8);
  padding: 20px 25px;
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.4);
  text-align: center;
  min-width: 120px;
  backdrop-filter: blur(20px);
  transition: all 0.3s ease;
  border: 1px solid rgba(255,255,255,0.1);
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0,0,0,0.2);
}

.stat-number {
  font-size: 36px;
  font-weight: 800;
  color: #4FC3F7;
  margin-bottom: 8px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.5);
}

.stat-label {
  font-size: 16px;
  color: rgba(255,255,255,0.8);
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.resident-detail {
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .collapsible-toolbar.expanded {
    width: 320px;
  }
  
  .stats-panel {
    gap: 8px;
  }
  
  .stat-card {
    padding: 10px 12px;
    min-width: 60px;
  }
  
  .stat-number {
    font-size: 18px;
  }
}

@media (max-width: 768px) {
  .map-header {
    height: 60px;
    padding: 0 15px;
  }
  
  .map-title {
    font-size: 18px;
  }
  
  .collapsible-toolbar {
    top: 10px;
    right: 10px;
    width: 50px;
    height: 50px;
  }
  
  .collapsible-toolbar.expanded {
    width: 280px;
    min-height: 180px;
  }
  
  .toolbar-toggle {
    width: 50px;
    height: 50px;
  }
  
  .toolbar-content {
    padding: 15px;
    padding-top: 65px;
    gap: 18px;
  }
  
  .group-content {
    flex-direction: column;
    align-items: stretch;
    gap: 6px;
  }
  
  .group-content .el-input {
    width: 100% !important;
  }
  
  .stats-panel {
    top: 10px;
    left: 10px;
    gap: 6px;
    flex-wrap: wrap;
  }
  
  .stat-card {
    padding: 8px 10px;
    min-width: 50px;
  }
  
  .stat-number {
    font-size: 16px;
  }
  
  .stat-label {
    font-size: 11px;
  }
}
</style> 